import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";

@Injectable({
  providedIn: 'root'
})
export class ElasticSearchService {

  constructor(
    private http: HttpClient,
  ) {
  }

  getToken(param: { password: string; url: string; authentication: boolean; username: string }): string {
    return btoa(`${param.username}:${param.password}`)
  }

  getTokenFromCache() {
    const configuration = this.getConfiguration();
    return configuration?.token;
  }

  getOptions(param: { password: string; url: string; authentication: boolean; username: string }) {
    return {
      headers: {
        Authorization: `Basic ${this.getToken(param)}`
      }
    }
  }

  getOptionsFromCache() {
    return {
      headers: {
        Authorization: `Basic ${this.getTokenFromCache()}`
      }
    }
  }

  saveConfiguration(param: { password: string; url: string; authentication: boolean; username: string }) {
    const configuration = {
      url: param.url,
      token: `${this.getToken(param)}`
    }
    localStorage.setItem('configuration', JSON.stringify(configuration))
  }

  haveConfiguration() {
    return !!localStorage.getItem('configuration');
  }

  getConfiguration(): { url: string, token: string } | null {
    const configuration = localStorage.getItem('configuration');
    if (!configuration) {
      return null
    }
    return JSON.parse(configuration)
  }

  saveAuthentication(authentication: any) {
    localStorage.setItem('authentication', JSON.stringify(authentication))
  }

  checkAuthentication(param: { password: string; url: string; authentication: boolean; username: string }) {
    return this.http.get(`${param.url}/_security/_authenticate`, this.getOptions(param))
  }

  getAuthentication() {
    const authentication = localStorage.getItem('authentication');
    if (!authentication) {
      return null
    }
    return JSON.parse(authentication)
  }

  getRequest(url: string) {
    const configuration = this.getConfiguration();
    return this.http.get(`${configuration?.url}${url}`, this.getOptionsFromCache())
  }
}
